These notes cover the classical core of machine learning — regression, classification and clustering — and follow one thread through all three. We first fit a line to data and understand the fit three ways — geometrically, analytically, and probabilistically. Then we bend the same machinery until the output is a probability rather than a number, and regression becomes classification. After that we take classification on its own terms — hyperplanes, margins, trees — learn how to grade a classifier, and finally remove the labels altogether and let the data group itself.
Suppose we have $n$ data points, $x_1,\cdots,x_n$, in $\mathbb{R}^p $, denote $$\mathbf{X} \in \mathbb{R}^{n\times p }$$ the matrix with entries given by $$\mathbf{X}_{i,j}=(x_i)_j$$ For each point, $x_i$, there is a corresponding output $y_i$; we denote the output vector by $$\mathbf{y} := \begin{pmatrix} y_1\\\vdots\\y_n \end{pmatrix}$$ Denote the design matrix $$X:=[\mathbf{X}|\mathbb{1}] \in \mathbb{R}^{n\times (p+1) }$$ The goal of a least-squares problem is to find the vector $\mathbf{\beta}\in \mathbb{R}^{p+1}$ that minimizes the Sum of Squared Error $$\mathrm{SSE}(w):=\|X w - \mathbf{y}\|_2^2 $$
The identity $SST = SSE + SSR$ is Pythagoras in the geometry above: with an intercept in the model, the residual $\mathbf{y} - \widehat{\mathbf{y}}$ is orthogonal to the whole column space, hence to $\widehat{\mathbf{y}} - \overline{\mathbf{y}}$, so the centered response splits into perpendicular fitted and residual parts — and $R^2$ is the squared cosine of the angle between them, equivalently the squared correlation of $\mathbf{y}$ and $\widehat{\mathbf{y}}$. Two corrections keep $R^2$ honest. It never decreases when a feature is added, even a useless one, so comparisons across model sizes use the adjusted $R^2$, $\bar R^2 = 1 - (1 - R^2)\frac{n - 1}{n - p - 1}$, which charges each feature its degree of freedom. And the $F$ above specializes to the test of the whole regression against the intercept-only model: $F = \frac{R^2 / p}{(1 - R^2)/(n - p - 1)}$; for a single coefficient it reduces to $F = t^2$, the square of that coefficient's $t$-statistic.
Detection. Compute $\mathrm{VIF}_j$ for every feature — it needs only the design, not $\mathbf{y}$. Values above $5$ or $10$ (that is, $R_j^2$ above $0.8$ or $0.9$) are the usual rules of thumb for concern. A single-number summary is the condition number $\kappa(X) = s_{\max}/s_{\min}$ of the design's singular values: near collinearity is exactly a small $s_{\min}$, and $\kappa$ above roughly $30$ on scaled features signals the same problem.
Remedies. Drop or combine the redundant features when one of them carries no separate meaning; replace the entangled block by its principal components, which are orthogonal by construction (at the cost of interpreting components instead of features); collect data that breaks the near-dependence, the only remedy that adds information; or shrink — ridge regression, in Regularizations below, adds $\lambda I$ to $X^TX$ before inverting, which is precisely a floor under the small singular values, trading a little bias for a large variance cut along exactly the directions multicollinearity inflates.
The formula above, measured instead of asserted. The design is $n = 400$ points with $y = x_1 + x_2 + \varepsilon$, $\sigma = 1$, where $x_2 = \rho z_1 + \sqrt{1-\rho^2}\, z_2$ is built from one seeded pair $(z_1, z_2)$ — the same points at every $\rho$ (common random numbers, seed 20261123), only more or less entangled. The design then stays fixed while $200$ seeded noise draws are refit: the spread of $\widehat\beta_1$ across those resamples is its standard error, computed rather than quoted. The slider sets $\rho$; the third panel grades the measured spread against the section's $\sigma/\sqrt{(1-\rho^2) S_1}$ at every stop.
At every stop the measured spread sits within a few percent of the formula — $0.162$ against $0.160$ at $\rho = 0.95$, $0.365$ against $0.354$ at $\rho = 0.99$ — so the inflation is real arithmetic, not a rule of thumb. And the control group is in the readout: $\mathrm{sd}(\widehat\beta_1 + \widehat\beta_2)$ goes from $0.071$ at $\rho = 0$ to $0.046$ at $\rho = 0.99$, flat to slightly better, while $\mathrm{sd}(\widehat\beta_1)$ grows eightfold. The shared direction is estimated as well as ever; only the split between the two coefficients is lost — at $\rho = 0.99$, $\widehat\beta_1$ comes out below $0.5$ in $15$ of the $200$ resamples and negative in $3$, with the truth at $1$. That is the section's distinction made visible: prediction survives multicollinearity, attribution does not.
For ideas behind the Gradient Descent Algorithm, see the page Optimization Methods. In the example, we applied the Gradient Descent algorithm to minimize $\mathrm{SSE}(b)$. The updating rule is given by $$b_{j+1}=b_{j}-\alpha X^{T}(Xb-Y)$$
The Hessian of $\mathrm{SSE}$ is given by $$H_\mathrm{SSE}(b)=J_{\nabla \mathrm{SSE}}( b )=2X^TX$$ Thus $H_\mathrm{SSE} (b)$ is positive definite, locally by the Derivative Test, any local optimum of $\mathrm{SSE}(b)$ will be a local minimum. And globally $H_\mathrm{SSE} (b) $ positive definite for all $b$ implies $\mathrm{SSE}(b)$ is convex , and thus our local minimum is the unique global minimum.Let $\mathbf{x}$ be a Gaussian random variable with mean $1$, and we observe 4 realizations of $\mathbf{x}$
Which of the following choices is a more likely distribution for $\mathbf{x}$?
One dataset, eight predictors, every penalty on this page. The loss is the one above — $\mathrm{RSS} + \lambda\big(\alpha\sum_j|\beta_j| + (1-\alpha)\sum_j\beta_j^2\big)$ — fit on standardized predictors with an unpenalized intercept. Drag $\lambda$ and watch each coefficient travel its path: at the left edge ($\lambda \to 0$) every path lands on the least-squares estimate; at the right edge the penalties win. Two of the eight predictors are decoys — $x_7$ is pure noise, and $x_8$ only shadows $x_1$ — and $x_3, x_4$ are a correlated pair ($\rho \approx 0.96$) carrying one shared effect.
Three things worth noticing. Lasso's paths hit zero exactly and stay there — that is the feature selection the text above promises, and the decoys $x_7, x_8$ are usually the first to go. The correlated pair behaves differently under each penalty: lasso tends to keep one of $x_3, x_4$ and kill the other, elastic net shares the effect between them (the grouping effect), and ridge shrinks both together. And ridge's paths only approach zero — no finite $\lambda$ sets a ridge coefficient to exactly zero, which is why ridge never selects.
The explorer above leaves one question open: which $\lambda$? The training error cannot answer — it falls monotonically as $\lambda$ shrinks, because the fit is grading its own homework. The estimate has to come from data the fit has not seen. $K$-fold cross-validation manufactures such data: split the sample into $K$ folds, fit on the other $K-1$, score the held-out fold, rotate, and average: $$\mathrm{CV}_K(\lambda) = \frac{1}{n}\sum_{i=1}^{n} \Big(y_i - \hat f^{-\kappa(i)}_{\lambda}(\mathbf{x}_i)\Big)^2,$$ where $\kappa(i)$ is the fold containing point $i$ and the $-\kappa(i)$ on the hat means the fit that never saw point $i$. The working rule is then simply choose the $\lambda$ that minimizes $\mathrm{CV}_K(\lambda)$ — and the same procedure tunes $\alpha$, a tree's depth, or any other hyperparameter: anything with a knob gets a CV curve.
Two refinements matter in practice. The CV curve is itself an estimate, with a standard error across the folds; the one-standard-error rule picks the largest $\lambda$ whose CV error lies within one standard error of the minimum — the most strongly shrunk model the data cannot distinguish from the best. And the extreme $K = n$, leave-one-out, needs no refitting at all for a linear smoother like ridge: with $e_i$ the ordinary residuals of the single full fit and $h_{ii}$ the diagonal of the hat matrix, $$\mathrm{LOO}(\lambda) = \frac{1}{n}\sum_{i=1}^{n} \left(\frac{e_i}{1 - h_{ii}}\right)^{\!2},$$ because a point's leave-one-out residual is its ordinary residual inflated by $1/(1 - h_{ii})$ — its own leverage handed back. (Generalized cross-validation replaces every $h_{ii}$ by their average, $\mathrm{tr}(H)/n$.)
One honesty note. The CV value at the chosen $\hat\lambda$ is not quite an honest error estimate for the chosen model: it mixes two small biases — the folds train on only $n(K-1)/K$ points (slightly pessimistic) while $\hat\lambda$ won a contest judged on these very folds (slightly optimistic). An untouched test set, or an outer loop around the whole selection (nested CV), settles the number. The demo below cheats in your favor: it shows the test set.
One dataset — $n = 48$ points, $p = 12$ predictors of which seven are pure noise, noise level $\sigma = 1.5$ — and ridge fits along the whole $\lambda$ grid. Grey is the training error, which always votes for $\lambda \to 0$. Navy is the cross-validation estimate, with its $\pm 1$ SE band. Green, dashed, is the truth no practitioner gets to see: the mean squared error on 4,000 fresh points. At the left edge the training error reads $1.57$ against an honest $\approx 2.9$ — that gap is the overfit, measured. Watch how the navy curve tracks the green one's valley, and how flat that valley is.
At the default 5-fold setting, CV picks $\lambda = 1.78$ — on this sample, exactly where the test curve bottoms out ($2.86$); 10-fold and leave-one-out pick $\lambda = 3.16$ and land within a percent of that optimum. The one-standard-error rule is visibly more conservative, taking $\lambda = 10$: the extra shrinkage costs real error here (test $3.26$ against $2.86$), which is the rule's known character — it buys simplicity, and with ridge there is little simplicity to buy. Draw a new sample and the picks move, but the shape does not: a flat valley between two ditches. Finding that valley — and staying out of the ditches — is the whole of what tuning is.
The cross-validation curve above has a valley because the test error it estimates is a sum of two curves pulling opposite ways. For a fit $\hat f$ trained on a random sample, the expected squared error at a point splits exactly: $$\E\big[(y - \hat f(x))^2\big] = \underbrace{\big(\bar f(x) - f(x)\big)^2}_{\text{bias}^2} + \underbrace{\Var\big(\hat f(x)\big)}_{\text{variance}} + \underbrace{\sigma^2}_{\text{noise}},$$ where $\bar f$ is the average fit over all possible training samples. Cross-validation can only see the total; this demo knows the truth — $f(x) = \sin 2\pi x - 0.6\cos 2\pi x + 0.4(x - \tfrac12)$, sampled at $n = 25$ fixed points with noise $\sigma = 0.5$ — so it can draw the split. For each polynomial degree it refits $80$ fresh datasets: the average fit against the truth is the bias, the spread of the fits is the variance, and the three components on the right are averaged over the input range. It is the same U the CV curve traces, opened up.
The linear model can be pushed beyond a Gaussian response. Change the response distribution and add a link function, and the same machinery estimates probabilities instead of values — regression turns into classification. We cross that bridge first (logistic regression), then step back to the framework behind it (generalized linear models), and close with a second, orthogonal generalization: random effects for grouped data (mixed models).
In Logistic Regression, we assume for some parameter $\theta$,
$$y\sim
\mathtt{Bernoulli}(p_\theta(\mathbf{x}))$$
Recall that the odds of $y=1$ conditioned on $\mathbf{x}$ is given by
$$\frac{\mathtt{Pr}(y=1\mid \mathbf{x})}{\mathtt{Pr}(y=0\mid \mathbf{x})}=
\frac{p_\theta(\mathbf{x})}{1-p_\theta(\mathbf{x})}\geq 0$$
Consider applying the monotonic function $\log$ to the above, we get the log-odds of
$y=1$ or equivalently the logit function
on $p_\theta(\mathbf{x})$, i.e.
$$\mathtt{logit}(p_\theta(\mathbf{x})):=\log\left(\frac{p_\theta(\mathbf{x})}{1-p_\theta(\mathbf{x})}\right)\in
\mathbb{R}$$
and the key assumption is that the log-odds is a linear function of
$\mathbf{x}$, i.e.
$$\log\left(\frac{p_\theta(\mathbf{x})}{1-p_\theta(\mathbf{x})}\right)=\theta\cdot \mathbf{x}$$
thus by the above assumptions, we have
$$p_\theta(\mathbf{x})= \frac{1}{1+\exp(-\theta\cdot
\mathbf{x})}=:\mathtt{sigmoid}(\theta\cdot \mathbf{x})$$
Here sigmoid is the inverse of the logit function.
And the goal of logistic regression is to estimate the probabilities $p_\theta(\mathbf{x})$.
Since the sigmoid function is not linear, it is more convenient to use MLE to estimate
$\theta$.
Maximizing the likelihood function is equivalent to minimizing the negative log-likelihood
$$L(\theta)=-\sum_{i=1}^{n} \left[ y^{(i)} \log \left(p_\theta(\mathbf{x}^{(i)})\right)+\left(1-y^{(i)}\right) \log
\left(1-p_\theta(\mathbf{x}^{(i)})\right)\right]$$
The summands are$$\begin{cases}\log \left(p_\theta(\mathbf{x}^{(i)})\right),\qquad &
y^{(i)}=1\\
\log \left(1-p_\theta(\mathbf{x}^{(i)})\right) & y^{(i)}=0 \end{cases}
$$
The above loss function is also known as the Binary Cross Entropy function.
Using Gradient Descent, we get the following updating rule $$\theta_{j+1}=\theta_{j}-\alpha
X^{T}(p_\theta(X)-Y)$$
Where $X$ is the design matrix.
The logistic regression model can be expressed as:
$$ \log\left(\frac{P(y=1)}{1-P(y=1)}\right) = \beta_0 + \beta_1 x_1 + \beta_2 x_2 + \cdots + \beta_n x_n $$ Taking the exponential of both sides, we get: $$ \begin{align} \text{odds}(y=1) &= \exp(\beta_0 + \beta_1 x_1 + \beta_2 x_2 + \cdots + \beta_n x_n)\\ &= \exp(\beta_0)\exp(\beta_1 x_1)\exp(\beta_2 x_2)\cdots\exp(\beta_n x_n) \end{align} $$ The exponential of the coefficients $$\exp(\beta_j)$$ gives the relation between the odds of $y=1$ and the corresponding feature $x_j$.A Generalized Linear Model is of the form $$\eta(\mu_{\bf x}):=\eta\left(\mathrm{E}\left(Y \mid \bf x\right)\right)= \theta \cdot \bf x',\qquad \bf x' = \begin{pmatrix}1\\ \bf x \end{pmatrix} $$ for some link function $\eta$, and we assume that the entries of $ Y$ are independently sampled from an exponential family.
A common choice is $\eta = \log$, used when $Y$ is non-negative; the model can then be expressed as:
$$ \mu_{\bf x} = \exp\left(\beta_0 + \beta_1 x_{1} + \beta_2 x_{2} + \cdots + \beta_p x_{p}\right) = e^{\beta_0} \times e^{\beta_1 x_{1}} \times \cdots \times e^{\beta_p x_{p}} $$
import statsmodels.api as sm
import statsmodels.formula.api as smf
# Example data
data = sm.datasets.get_rdataset("dietox", "geepack").data
# Fit model
model = smf.mixedlm("Weight ~ Time", data, groups=data["Pig"])
results = model.fit()
# Predict fixed-effects only
fixed_predictions = results.predict(data)
# Predict with random effects
random_effects = results.random_effects
group_predictions = fixed_predictions + data["Pig"].map(random_effects)
We now take classification on its own terms: find a separating rule, and judge it by the geometry of its boundary — a hyperplane learned by correction (the perceptron), a maximum-margin hyperplane (the SVM), or an ensemble of decision trees (bagging, random forests, XGBoost). The probabilistic classifier, logistic regression, was already built as the bridge in II. The last chapter of this part asks how a finished classifier should be graded.
One of the earliest algorithms for classification problems is the Perceptron Algorithm.
Initialize: $$\widehat{\mathbf{w}} = 0$$
while $\exists\ \widehat{\mathbf{x}}_{\mathbf{i}}$ with $\widehat{\mathbf{x}}_{\mathbf{i}} l_{i} \cdot
\widehat{\mathbf{w}}
\leq 0$,
update $$\widehat{\mathbf{w}} \leftarrow \widehat{\mathbf{w}}+\widehat{\mathbf{x}}_{\mathbf{i}} l_{i}$$
As long as the points are linearly separable, i.e. a solution exists, the Perceptron Algorithm is guaranteed to stop and find a solution.
The guarantee comes with a rate, and the rate is a statement about geometry, not about the sample size. Suppose some unit vector $\mathbf{u}$ separates the (augmented) points with margin $\gamma > 0$, $$l_i\,(\mathbf{u}\cdot\widehat{\mathbf{x}}_i)\ge \gamma\quad\text{for all }i,$$ and every point lies in a ball of radius $R$, $\|\widehat{\mathbf{x}}_i\|\le R$. Then the number of updates the algorithm ever makes is at most $$\left(\frac{R}{\gamma}\right)^{2}$$ (Block, 1962; Novikoff, 1962). The proof is two lines of bookkeeping on the weight vector $\mathbf{w}_k$ after $k$ updates. Each update adds a misclassified point, so the alignment with $\mathbf{u}$ grows by at least $\gamma$ per update, $\mathbf{w}_k\cdot\mathbf{u}\ge k\gamma$; but the update is triggered exactly when $l_i(\mathbf{w}\cdot\widehat{\mathbf{x}}_i)\le 0$, so the squared length grows by at most $R^{2}$ per update, $\|\mathbf{w}_k\|^{2}\le kR^{2}$. Cauchy–Schwarz, $k\gamma\le \mathbf{w}_k\cdot\mathbf{u}\le\|\mathbf{w}_k\|\le R\sqrt{k}$, forces $k\le (R/\gamma)^{2}$.
Three consequences are worth keeping. First, the bound involves neither the number of points $n$ nor the dimension $p$: a wide-margin problem is learned after few mistakes however large the dataset, while a barely separable one ($\gamma$ near $0$) can take arbitrarily long — separability alone promises termination, the margin promises it soon. Second, the bound is scale-free: multiplying every point by a constant multiplies $R$ and $\gamma$ alike and changes nothing. Third, the hyperplane the algorithm stops at is a separator, whichever one the order of presentation happens to reach — nothing in the update prefers a large margin. Choosing the separator with the largest margin is a different, harder problem, and it is exactly the one the Support Vector Machines section below takes up. On non-separable data the loop above never exits: the algorithm cycles forever, which is the practical motivation for the kernel method that follows and, later, for soft margins.
The bound above, watched as it happens. Two seeded strips of $120$ points each face off across a gap: every point's distance from the midline is $\gamma_0 + 0.6 \cdot u$ with $u$ uniform, so the midline separates the sample with margin $\gamma$ just above $\gamma_0$ — the slider sets $\gamma_0$, moving the same points (common random numbers, seed 20261122) apart or together. The presentation order is one fixed seeded shuffle, $\mathbf{w}$ starts at $0$, and each Step is one update — one misclassified point added to $\mathbf{w}$. The readout grades the running update count against $(R/\gamma)^2$ with $R$ and $\gamma$ measured on the sample itself. The checkbox instead flips the six points nearest the midline on each side — a few mislabeled points, and no separator exists at all.
Across the slider the update counts run $18, 10, 8, 4, 3, 2$ against bounds $308, 80, 30, 16, 10, 7$: the theorem always holds, and always with room to spare — it is a worst case over presentation orders, and this order is ordinary. The separators the algorithm stops at are usually worse than the midline it was graded against (at $\gamma_0 = 0.7$ its margin is $0.029$ against the midline's $0.701$): it stops at the first separator the order reaches, exactly as the prose above says, and leaves the good one to the SVM section. The mislabeled variant makes the opposite point: $331$ updates by epoch $30$, about $11$ more every epoch, no clean pass in sight — with no $\gamma$ there is no bound, and the loop simply never exits.
The primary goal in SVM classification is to find the optimal hyperplane $$\mathbf{w}^T \mathbf{x} + b = 0$$ that maximizes the margin between two classes. For linearly separable data, this reduces to solving the quadratic optimization problem:
where $y_i \in \{-1, 1\}$ are class labels. The support vectors (critical training samples closest to the hyperplane) define the margin boundaries $$\mathbf{w}^T \mathbf{x} + b = \pm 1$$.
For non-separable data, soft margin SVM introduces slack variables $\xi_i$ and a regularization parameter $C$:
This balances margin width and classification error.
When data isn't linearly separable, SVMs use kernel functions $K(\mathbf{x}_i, \mathbf{x}_j) = \phi(\mathbf{x}_i)^T \phi(\mathbf{x}_j)$ to map features into higher dimensions without explicit computation.
The trick is available because the SVM never needs $\phi$ itself — only inner products between mapped points. Solving the dual of the soft-margin problem above makes this plain: the solution has the form $\mathbf{w} = \sum_i \alpha_i y_i \phi(\mathbf{x}_i)$, and the dual objective $$\max_{\alpha} \; \sum_{i=1}^n \alpha_i - \frac{1}{2} \sum_{i,j} \alpha_i \alpha_j y_i y_j \, \phi(\mathbf{x}_i)^T \phi(\mathbf{x}_j) \quad \text{subject to} \quad 0 \le \alpha_i \le C, \;\; \sum_i \alpha_i y_i = 0$$ involves the mapped points only through their pairwise inner products. Replacing each inner product by $K(\mathbf{x}_i, \mathbf{x}_j)$ — any kernel from the Kernel Method section above, Mercer's condition being what guarantees a $\phi$ exists — trains the machine in the high-dimensional space while every computation stays in the original one. The classifier itself is a kernel expansion, $$f(\mathbf{x}) = \sgn\Big( \sum_{i=1}^n \alpha_i y_i K(\mathbf{x}_i, \mathbf{x}) + b \Big),$$ and since $\alpha_i > 0$ only for the support vectors, prediction costs one kernel evaluation per support vector, not per training point.
What is saved is the size of $\phi$. For the degree-2 polynomial kernel on $\mathbb{R}^2$ the map $\phi(\mathbf{x}) = (x_1^2, \sqrt{2}\, x_1 x_2, x_2^2,$ $\sqrt{2c}\, x_1, \sqrt{2c}\, x_2, c)$ is already six-dimensional, and in general a degree-$q$ polynomial kernel on $\mathbb{R}^p$ has $\binom{p+q}{q}$ coordinates — $66$ for $p = 10$, $q = 2$ — while the kernel value $(\mathbf{u} \cdot \mathbf{v} + c)^q$ costs one inner product. The Gaussian kernel goes further: expanding its cross term, $e^{\mathbf{u} \cdot \mathbf{v} / \sigma^2} = \sum_{k=0}^{\infty} \frac{(\mathbf{u} \cdot \mathbf{v})^k}{\sigma^{2k} k!}$, shows every polynomial degree present at once, so its $\phi$ is infinite-dimensional and no explicit map exists to compute with. Back in the original space the boundary $f(\mathbf{x}) = 0$ is a curved level set — a weighted sum of bumps centred on the support vectors, for the Gaussian kernel — which is exactly the nonlinear separation the primal could not express.
The costs move rather than vanish: training works with the $n \times n$ Gram matrix of all pairwise kernel values, so memory and solve time grow superlinearly in $n$, and the kernel's own parameters — the bandwidth $\sigma$ (equivalently $\gamma = 1 / 2\sigma^2$) alongside $C$ — are hyperparameters, chosen by the cross-validation of Part I like every penalty on this page.
At the core of Random Forest lies bagging, a resampling technique that generates multiple training datasets from the original data. For a dataset $D = \{(x_1, y_1), \ldots, (x_n, y_n)\}$, bagging creates $B$ bootstrap samples $D_1, D_2, \ldots, D_B$ by sampling $n$ instances with replacement from $D$. Each bootstrap sample has an expected overlap of $1-\frac{1}{e}$ with the original dataset.
For each bootstrap sample $D_b$, a decision tree $f_b(x)$ is trained. The final prediction is an aggregate of these individual trees:
This aggregation reduces variance by averaging out the noise inherent in individual trees.
Random Forest introduces feature randomness by selecting a random subset of features at each split. For a dataset with $d$ features, each tree is trained on a subset of size $k = \sqrt{d}$ (classification) or $k = \frac{d}{3}$ (regression). This randomness decorrelates trees, further reducing variance while preserving bias.
The probability $p_{nj}$ of selecting the $j$-th feature at a node determines the level of randomness. If $p_{nj} \in (0, 1)$, the correlation $\rho(x)$ between trees decreases, leading to lower variance in the ensemble.
Feature importance in Random Forest is often measured by the mean decrease in impurity across all trees. For feature $j$, the importance is:
where $\Delta \text{Impurity}_{n}(j)$ is the reduction in impurity at node $n$ due to splitting on feature $j$.
XGBoost minimizes the loss function $L(y_i, F(x_i))$, where $F(x) = \sum_{m=1}^{M} f_m(x)$ is the ensemble of decision trees. At each iteration $m$, the algorithm approximates the loss using a second-order Taylor expansion:
The approximated objective function becomes:
where $\Omega(f_m)$ is the regularization term to control overfitting:
This term discourages deep trees (via $\gamma T$) and large leaf weights (via $\lambda \sum w_j^2$).
Feature importance is measured by the gain in loss reduction when splitting on a feature. For XGBoost, when a node is split into left and right children with instance sets $I_L$ and $I_R$, write $G_L = \sum_{i \in I_L} g_i$ and $H_L = \sum_{i \in I_L} h_i$ for the sums of the gradients and Hessians over the left child, and $G_R$, $H_R$ similarly over the right child. The gain of the split is:
This gain is accumulated across all trees to rank feature contributions.
In classification tasks, it is important to evaluate the performance of the model using various metrics. Three commonly used metrics are precision, recall, and F1 score.
These metrics help in understanding the performance of a classification model, especially in cases where the class distribution is imbalanced.
Precision, recall and the F1 score all judge a classifier at one fixed threshold. A scoring classifier, though, is a family of classifiers — one per threshold — and the ROC curve evaluates the whole family at once. For a threshold $t$, call an instance positive when its score exceeds $t$ and record the two rates $$ \text{TPR}(t) = \frac{\text{True Positives}}{\text{True Positives} + \text{False Negatives}}, \qquad \text{FPR}(t) = \frac{\text{False Positives}}{\text{False Positives} + \text{True Negatives}} $$ — the TPR is the recall of the previous section; the FPR is the fraction of actual negatives the threshold wrongly admits. Sweeping $t$ from $+\infty$ (nothing is called positive: the point $(0, 0)$) down to $-\infty$ (everything is: $(1, 1)$) traces the curve through the unit square, monotone non-decreasing as the threshold falls.
The AUC is the area under that curve, $$ \text{AUC-ROC} = \int_0^1 \text{TPR}(t) d \text{FPR}(t) = \int_0^1 \text{TPR}(FPR^{-1}(t)) dt $$ and it has a second, purely combinatorial reading: the AUC is the probability that the classifier ranks a random positive above a random negative, $$ \text{AUC} = \Pr(S_p > S_n) + \tfrac{1}{2} \Pr(S_p = S_n) = \frac{U}{n_p n_n}, $$ where $S_p$ and $S_n$ are the scores of positive and negative instances, $n_p$ and $n_n$ their counts, and $U$ the Mann–Whitney statistic — the number of correctly ordered positive–negative pairs, ties counting half. The two readings are the same number: with positive scores $\{0.9, 0.7, 0.4\}$ and negative scores $\{0.8, 0.3, 0.2\}$, exactly $7$ of the $9$ pairs are correctly ordered, and the trapezoid area under the ROC curve is likewise $7/9 \approx 0.78$.
Three landmarks calibrate the scale: a perfect ranking has AUC $1$; scores unrelated to the label give the diagonal and AUC $1/2$; an AUC below $1/2$ means the ranking is inverted — negating the score beats the classifier. Because both rates are computed within a class, the AUC is a property of the ranking alone: it does not depend on the threshold, on the class prevalence, or on whether the scores are calibrated probabilities. Those are also its limits. It says nothing about calibration, and under heavy imbalance a small FPR can still correspond to many false positives in absolute terms — the regime where the precision–recall curve, built from the precision of the previous section, is the sharper instrument.
The sweep above, run. Sixty negatives score $\mathcal{N}(0, 1)$ and sixty positives $\mathcal{N}(d, 1)$ (seed 20261124, the same draws at every $d$), with every score rounded to one decimal, the way a real classifier's output arrives — the rounding manufactures genuine ties, so the $\tfrac12$ in the section's formula does real work. The slider sets the separation $d$; Run or Step lowers the threshold one score level at a time, and at each level the ROC point jumps — diagonally whenever a level holds both classes, which is the tie term happening. At the end the AUC is read out both ways at once: the trapezoid area under the traced curve, and the pair count $U/(n_p n_n)$.
At every separation the two readings agree to the last printed digit — at the default $d = 1.5$, trapezoid $0.8756$ and pairs $3152/3600 = 0.8756$, with $58$ tied pairs contributing their halves through the diagonal jumps. The empirical values run a little above the unrounded normal model's $\Phi(d/\sqrt{2})$ ($0.856$ at $d = 1.5$): rounding costs almost nothing, but $60$ scores a class is a small sample — at $d = 0$, where the ranking is pure noise, this sample still scores $0.554$, and the AUC's own standard error at that size is about $0.05$. The curve is a property of the ranking; the number read off a finite sample is an estimate of it.
Finally, the labels come off. With no target to predict, the problem is to discover structure in the points themselves: partition them around moving centers (k-means), follow the density and let the clusters take whatever shape they like (DBSCAN), or follow the density at every level at once and keep the clusters that persist (HDBSCAN).
k-Means Algorithm is one of the earliest methods developed for clustering problems, and is still the most popular partitioning algorithm today.
K-means partitions by distance to a center, so its clusters are convex and every point is assigned — including points that belong nowhere. DBSCAN (Ester, Kriegel, Sander & Xu, 1996) replaces the center with a density test. Fix a radius $\epsilon$ and a count MinPts. A point is a core point if at least MinPts points lie within distance $\epsilon$ of it; a point within $\epsilon$ of a core point but not itself core is a border point; anything else is noise. A cluster is a maximal set of points chained together through overlapping core neighborhoods — density-connected, in the paper's term — so a cluster may bend, branch, or wrap around another one, and noise is left unassigned instead of being forced into a cluster.
The demo below makes the contrast concrete: its data are two concentric rings. No choice of two centers separates them — k-means with $k = 2$ cuts both rings roughly in half, since each center attracts the nearer half of each ring. DBSCAN follows the density along each ring and recovers both. The same experiment, run offline with $\epsilon = 0.12$ and MinPts $= 5$ on 300 points per ring plus 40 uniform noise points, labels every ring point correctly and rejects most of the noise (26 of 40; the rest happen to fall within $\epsilon$ of a ring and are absorbed as border points).
The price is the two parameters, and one global density threshold. MinPts is the smoothing choice: the usual heuristic is MinPts $\ge d + 1$ in dimension $d$, with larger values suppressing noise at the cost of thinning sparse clusters. Given MinPts, $\epsilon$ is commonly read off a $k$-distance plot — the sorted distance to each point's MinPts-th nearest neighbor — at the knee where the sparse tail takes off. Because a single $(\epsilon, \text{MinPts})$ pair fixes one density level, clusters of very different densities defeat it: an $\epsilon$ small enough to split two tight clusters also dissolves a diffuse one. Distances themselves degrade in high dimensions, which thins the neighborhoods the test counts. With a spatial index the neighborhood queries cost $O(n \log n)$ overall; without one, $O(n^2)$.
DBSCAN's one global density level is the thing to give up. HDBSCAN (Campello, Moulavi & Sander, 2013) keeps the density idea and drops the fixed $\epsilon$: instead of asking which clusters exist at one threshold, it builds the clusters at every threshold and keeps the ones that persist. The construction starts by softening the metric itself. With MinPts fixed as before, each point's core distance is its distance to its MinPts-th nearest neighbor — small in dense regions, large in sparse ones — and the mutual reachability distance between two points is $d_{\text{mreach}}(a, b) = \max\{\text{core}(a), \text{core}(b), d(a, b)\}$. Nearby points in a dense region keep their true distance; any pair touching a sparse point is pushed apart to at least that point's core distance, so sparse points join the structure late instead of bridging two clusters early.
A minimum spanning tree of the complete graph under $d_{\text{mreach}}$, cut edge by edge from the longest down, is exactly the DBSCAN hierarchy: at cut level $\epsilon$ its components are the DBSCAN clusters for that $\epsilon$ (with single-linkage's chaining tamed by the reachability metric). Reparametrize the cut by $\lambda = 1/\epsilon$, so clusters are born at low $\lambda$ and split or dissolve as $\lambda$ grows, and prune the resulting tree with a second size parameter, MinClusterSize: a split in which a child keeps fewer than MinClusterSize points is not a split at all — those points simply fall out of the parent as noise. What remains is the condensed tree, whose nodes are the candidate clusters and whose edges record at which $\lambda$ each point left its cluster.
Selection is then a persistence contest. A candidate cluster $C$ born at $\lambda_{\text{birth}}$ earns stability $S(C) = \sum_{p \in C} (\lambda_p - \lambda_{\text{birth}})$, where $\lambda_p$ is the level at which point $p$ leaves $C$ — the total lifetime of its membership, summed over its points. Choose the non-overlapping set of candidates maximizing total stability: a parent is selected only if its stability beats the sum of its children's, otherwise the children win and the parent dissolves into them. The winners are the flat clustering — tight and diffuse clusters side by side, each found at its own density, which is precisely the configuration the single $(\epsilon, \text{MinPts})$ pair above cannot express. Points in no winning cluster are noise, as in DBSCAN.
The costs are honest ones. There are now two size parameters instead of a radius and a count, and while both are more forgiving than $\epsilon$ — the answer moves slowly as they vary — neither is automatic. The tree is built from all pairwise structure, so memory and time grow faster than DBSCAN's indexed neighborhood queries on large data. And stability is a global contest: a small cluster nested in the skirt of a large one can lose to its parent even when a reader would call it real. What the extra machinery buys is the removal of the one choice DBSCAN could not defend — the density level itself.
Two applications close the page, each reusing the machinery above: a time series regressed on its own past (ARIMA), and a rating matrix factorized into user and item embeddings (recommender systems).
An ARIMA$(p, d, q)$ model describes a time series $y_t$ through its own past values and past shocks. With $B$ the backshift operator ($B y_t = y_{t-1}$) and $\varepsilon_t$ white noise with variance $\sigma^2$, $$\phi(B)(1-B)^d y_t = c + \theta(B)\varepsilon_t, \qquad \phi(B) = 1 - \phi_1 B - \cdots - \phi_p B^p, \quad \theta(B) = 1 + \theta_1 B + \cdots + \theta_q B^q.$$
The three orders are:
The AR part is stationary iff every root of $\phi(z) = 0$ lies outside the unit circle, and the MA part is invertible iff every root of $\theta(z) = 0$ does.
The sample ACF (autocorrelation function) and PACF (partial autocorrelation function) fingerprint the orders:
Example — the yearly sunspot counts (309 observations, 1700–2008) are already close to stationary, so $d = 0$. An AR(2) fit, with estimated mean $\mu = 49.75$, gives $$(y_t - \mu) = 1.391\, (y_{t-1} - \mu) - 0.689\, (y_{t-2} - \mu) + \varepsilon_t, \qquad \sigma^2 = 274.7,$$ whose characteristic roots are complex with modulus $1.205$ — outside the unit circle, as stationarity requires — and complex roots mean the fitted dynamics oscillate: the implied pseudo-period is $\approx 10.9$ years, the celebrated sunspot cycle. A longer memory does even better on AIC: AR(9) scores $2570.6$ against the AR(2)'s $2622.6$, while differencing the series (ARIMA(1, 1, 1), AIC $2722.5$) only hurts — there was no trend to remove.
import statsmodels.api as sm
from statsmodels.tsa.arima.model import ARIMA
# Yearly sunspot counts, 1700-2008
y = sm.datasets.sunspots.load_pandas().data["SUNACTIVITY"]
# d = 0: model the (near-)stationary levels
res2 = ARIMA(y, order=(2, 0, 0)).fit()
print(res2.params) # const (the mean) 49.75, ar.L1 1.391, ar.L2 -0.689
print(res2.aic) # 2622.6
# A longer AR memory wins on AIC
res9 = ARIMA(y, order=(9, 0, 0)).fit()
print(res9.aic) # 2570.6
# Forecast the next 5 years
print(res2.get_forecast(5).predicted_mean)